package com.example.speech_recognition.activity;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.speech_recognition.GlideApp;
import com.example.speech_recognition.R;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.FaceRequest;
import com.iflytek.cloud.RequestListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.vondear.rxtools.view.dialog.RxDialogLoading;
import com.vondear.rxtools.view.dialog.RxDialogScaleView;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

public class FaceActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_face_avatar;
    private EditText et_face_name;
    private Button btn_face_register;
    private Button btn_face_verification;

    private Uri resultUri;
    private byte[] mImageData = null;
    // authid为6-18个字符长度，用于唯一标识用户
    private String mAuthid = null;

    private FaceRequest mFaceRequest;
    private RxDialogLoading dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);
        mFaceRequest = new FaceRequest(this);
        dialog = new RxDialogLoading(this, false, cancelListener);
        initView();
    }

    private DialogInterface.OnCancelListener cancelListener = new DialogInterface
            .OnCancelListener() {


        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mFaceRequest != null) {
                mFaceRequest.cancel();
            }
        }
    };

    private void initView() {
        iv_face_avatar = (ImageView) findViewById(R.id.iv_face_avatar);
        et_face_name = (EditText) findViewById(R.id.et_face_name);
        btn_face_register = (Button) findViewById(R.id.btn_face_register);
        btn_face_verification = (Button) findViewById(R.id.btn_face_verification);

        btn_face_register.setOnClickListener(this);
        btn_face_verification.setOnClickListener(this);

        Resources r = this.getResources();
        resultUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(R.drawable.circle_elves_ball) + "/"
                + r.getResourceTypeName(R.drawable.circle_elves_ball) + "/"
                + r.getResourceEntryName(R.drawable.circle_elves_ball));

        iv_face_avatar.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                RxDialogScaleView rxDialogScaleView = new RxDialogScaleView(FaceActivity.this);
                rxDialogScaleView.setImageUri(resultUri);
                rxDialogScaleView.show();
                return false;
            }
        });

        iv_face_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDialogChooseImage();
            }
        });
    }

    /**
     * 选择图片  从相册或者图库
     */
    private void initDialogChooseImage() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(FaceActivity.this, TITLE);
        dialogChooseImage.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }
                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }
                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                GlideApp.with(FaceActivity.this).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.DATA).
                        thumbnail(0.5f).
                        circleCrop().
                        placeholder(R.mipmap.circle_elves_ball).
                        priority(Priority.LOW).
                        error(R.mipmap.circle_elves_ball).
                        fallback(R.mipmap.circle_elves_ball).
                        into(iv_face_avatar);
                break;
            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    String path = resultUri.getPath();
                    mImageData = bitmap2Bytes(path);
                    roadImageView(resultUri, iv_face_avatar);
                    RxSPTool.putContent(FaceActivity.this, "AVATAR", resultUri.toString());
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 将uri 转换为二进制
     *
     * @param path 图片地址
     * @return byte[]
     */
    public byte[] bitmap2Bytes(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        GlideApp.with(FaceActivity.this).
                load(uri).
                diskCacheStrategy(DiskCacheStrategy.DATA).
                thumbnail(0.5f).
                circleCrop().
                placeholder(R.mipmap.circle_elves_ball).
                priority(Priority.LOW).
                error(R.mipmap.circle_elves_ball).
                fallback(R.mipmap.circle_elves_ball).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
//        options.setCircleDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    public void onClick(View v) {
        int ret = ErrorCode.SUCCESS;
        switch (v.getId()) {
            case R.id.btn_face_register:
                if (!dialog.isShowing()) {
                    dialog.show();
                }
                registerUser();
                break;
            case R.id.btn_face_verification:
                if (!dialog.isShowing()) {
                    dialog.show();
                }
                verificationUser();
                break;
            default:
                break;
        }
    }

    private void verificationUser() {
        mAuthid = et_face_name.getText().toString().trim();
        if (TextUtils.isEmpty(mAuthid)) {
            Toast.makeText(this, "用户id不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mImageData != null) {
            mFaceRequest.setParameter(SpeechConstant.AUTH_ID, mAuthid);
            mFaceRequest.setParameter(SpeechConstant.WFR_SST, "verify");
            mFaceRequest.sendRequest(mImageData, mRequestListener);
        } else {
            Toast.makeText(this, "请选择个人图片后注册", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 注册用户
     */
    private void registerUser() {
        mAuthid = et_face_name.getText().toString().trim();
        if (TextUtils.isEmpty(mAuthid)) {
            Toast.makeText(this, "用户id不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mImageData != null) {
            mFaceRequest.setParameter(SpeechConstant.AUTH_ID, mAuthid);
            mFaceRequest.setParameter(SpeechConstant.WFR_SST, "reg");
            mFaceRequest.sendRequest(mImageData, mRequestListener);
        } else {
            Toast.makeText(this, "请选择个人图片后注册", Toast.LENGTH_SHORT).show();
        }


    }

    private RequestListener mRequestListener = new RequestListener() {

        @Override
        public void onEvent(int eventType, Bundle params) {
        }

        @Override
        public void onBufferReceived(byte[] buffer) {

            try {
                String result = new String(buffer, "utf-8");
                Log.d("FaceDemo", result);

                JSONObject object = new JSONObject(result);
                String type = object.optString("sst");
                if (TextUtils.equals("reg", type)) {
                    register(object);
                } else if (TextUtils.equals("verify", type)) {
                    verify(object);
                } else if (TextUtils.equals("detect", type)) {
                    detect(object);
                } else if (TextUtils.equals("align", type)) {
                    align(object);
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO: handle exception
            }
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (dialog.isShowing()) {
                dialog.cancel();
            }
            if (error != null) {
                switch (error.getErrorCode()) {
                    case ErrorCode.MSP_ERROR_ALREADY_EXIST:
                        Toast.makeText(FaceActivity.this, "authid已经被注册，请更换后再试", Toast
                                .LENGTH_SHORT).show();
                        break;

                    default:
                        Toast.makeText(FaceActivity.this, error.getPlainDescription(true), Toast
                                .LENGTH_SHORT).show();
                        break;
                }
            }
        }
    };

    private void register(JSONObject obj) throws JSONException {
        int ret = obj.getInt("ret");
        if (ret != 0) {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("success".equals(obj.get("rst"))) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void verify(JSONObject obj) throws JSONException {
        int ret = obj.getInt("ret");
        if (ret != 0) {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("success".equals(obj.get("rst"))) {
            if (obj.getBoolean("verf")) {
                Toast.makeText(this, "通过验证，欢迎回来!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "验证不通过!", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void detect(JSONObject object) {

    }

    private void align(JSONObject object) {

    }
}
